package com.gpipe.dirwatcherRealtime;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.gpipe.dbwriter.SendResultData;
import com.gpipe.dirwatcher.DirectorySnapshot;
import com.gpipe.tools.GpipeInit;

public class ThreadRTRegionGo extends WriterThread {
//	String oneHourBFileTime=null;
	//lac|ci|nbr:lac|ci|nbr
	ConcurrentHashMap<String,String> getRecordsByFN = new ConcurrentHashMap<String, String>();

	public ThreadRTRegionGo(String name) {
		super(name);
		// TODO Auto-generated constructor stub
	}

	@Override
	protected void doWriting() {
		// TODO Auto-generated method stub
		String lastFileName = DirectorySnapshot.lastFileName.substring(
				DirectorySnapshot.lastFileName.indexOf("interface_")
						+ "interface_".length(),
				DirectorySnapshot.lastFileName.indexOf(".cdr"));
		Map<String, String> fileNames = new HashMap<String, String>();
		//region_id|area:nbrCount
		Map<String, Integer> resultMap = new HashMap<String, Integer>();
		fileNames = getFileName();
		
		Iterator<?> iter1 = fileNames.entrySet()
				.iterator();
		String nearFileName = null;
		if(DirectorySnapshotRealtime.goFileTimeBefore == null){
			while (iter1.hasNext()) {
				Map.Entry entry = (Map.Entry) iter1.next();
				String key = (String) entry.getKey();
				nearFileName = GpipeInit.returnnearFileName(lastFileName,key,nearFileName,DirectorySnapshotRealtime.statInterval);
			}
		}else{
			while (iter1.hasNext()) {
				Map.Entry entry = (Map.Entry) iter1.next();
				String key = (String) entry.getKey();
				int interval = GpipeInit.getInterval(key,DirectorySnapshotRealtime.goFileTimeBefore);
				if(interval>0){
					nearFileName = GpipeInit.returnnearFileName(lastFileName,key,nearFileName,DirectorySnapshotRealtime.statInterval);
				}
			}
		}
		iter1.remove();
		
		System.out.println("--##--timestamp of interval:"+nearFileName);
		
		DirectorySnapshotRealtime.goFileTimeBefore = nearFileName;
		try {
			getRecordsByFN = getLacCiByFN(nearFileName);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("--##--getRecordsByFN'size:"+getRecordsByFN.size());
		//general table3.2
		ThreadRTRegionCome threadRTRegionCome = new ThreadRTRegionCome("use a tool");
		resultMap = threadRTRegionCome.genData(getRecordsByFN, DirectorySnapshotRealtime.baseNbrArea);
		
		System.out.println("--##--nbrgo:"+resultMap.size());
		Iterator<?> iter2 = resultMap.entrySet()
				.iterator();
		while (iter2.hasNext()) {
			Map.Entry entry = (Map.Entry) iter2.next();
			System.out.println("--##--nbrgo-value:"+entry.getKey()+"|"+entry.getValue());
		}
		iter2.remove();
		
		String insertTruncate = new String("TRUNCATE TABLE subject_result_realtime_go_region");
    	String insertQuery = new String("INSERT INTO subject_result_realtime_go_region(region_id,area,nbr_num)VALUES(?,?,?)");
    	System.out.println("finish nbr go insert.");
    	SendResultData sendResultData = new SendResultData();
	    sendResultData.writeMysql(resultMap, insertQuery,3,insertTruncate,super.name,true);
		
//	    String fileName = super.name.toUpperCase()+"_"+nearFileName+".dat";
	    String fileName = super.name.toUpperCase()+"_"+DirectorySnapshotRealtime.fileNameSuffix+".dat";
	    sendResultData.writeLocFTP(resultMap, super.name, fileName,true);
	    
	    fileNames.clear();
	    resultMap.clear();
	}
	
	//select the timestamp of people's realtime flow for findind the timestampe one hour before.
	public Map<String, String> getFileName(){
		Map<String, String> result = new HashMap<String, String>();
    	SendResultData mysqlByProperty = new SendResultData();
    	Connection connection = mysqlByProperty.createConnect();
    	Statement stmt;
		try {
			stmt = connection.createStatement();
		 //创建Statement对象
        String sql = "select distinct filename from subject_result_realtime_base order by filename";    //要执行的SQL
        ResultSet rs = stmt.executeQuery(sql);//创建数据对象
            while (rs.next()){
                result.put(rs.getString(1), rs.getString(1));
            }
            rs.close();
            stmt.close();
            connection.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}
	
	private ConcurrentHashMap<String, String> getLacCiByFN(String filename) throws SQLException{
		ConcurrentHashMap<String, String> result = new ConcurrentHashMap<String, String>();
    	SendResultData mysqlByProperty = new SendResultData();
    	Connection connection = mysqlByProperty.createConnect();
    	Statement stmt = connection.createStatement(); //创建Statement对象
        String sql = "select lac,ci,acc_nbr from subject_result_realtime_base where filename = "+filename;    //要执行的SQL
        ResultSet rs = stmt.executeQuery(sql);//创建数据对象
            while (rs.next()){
                result.put(rs.getString(1)+"|"+rs.getString(2)+"|"+rs.getString(3), rs.getString(1)+"|"+rs.getString(2)+"|"+rs.getString(3));
            }
            rs.close();
            stmt.close();
            connection.close();
		return result;
	}
	

}
